import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

/**
 * @param initialSeconds 倒计时执行多少秒
 * @param timeInterval 间隔多少毫秒执行一次  默认1000毫秒
 * @param onTick()  没执行一次，回调一次该方法
 */
class CountdownTimer(
    private val initialSeconds: Int,
    private val timeInterval:Long = 1000,
    private val onTick: (remainingSeconds: Int) -> Unit = {},
    private val onFinish: () -> Unit = {}
) {
    private var remainingSeconds: Int = initialSeconds
    private var timeIntervalMill: Long = timeInterval
    private var job: Job? = null

    private val scope = CoroutineScope(Dispatchers.Main)

    fun start() {
        job = scope.launch {
            countdownFlow(initialSeconds)
                .onEach { time ->
                    remainingSeconds = time
                    onTick(time)
                }
                .onCompletion {
                    if (remainingSeconds == 0) onFinish()
                }
                .collect()
        }
    }

    fun stop() {
        job?.cancel()
        remainingSeconds = initialSeconds
    }

    fun isRunning(): Boolean {
        return job?.isActive == true
    }

    fun getRemainingSeconds(): Int {
        return remainingSeconds
    }

    private fun countdownFlow(seconds: Int): Flow<Int> = flow {
        for (time in seconds downTo 0) {
            emit(time)
            delay( timeIntervalMill)
        }
    }
}
